Laravel backpack InlineCreate Operation Method not allowed error - laravel-backpack

Trying to use inline_create i can create in modal but i can't select i get error
Method not allowed The POST method is not supported for this route.
Supported methods: GET, HEAD.
URL is : http://127.0.0.1:8000/admin/question/fetch/tags
Field
$this->crud->addField(
[
'label' => "Les mote clé",
'minimum_input_length' => 0,
'type' => 'relationship',
'name' => 'tags', // the method that defines the relationship in your Model
'ajax' => true,
// 'method' => 'GET',
'minimum_input_length' => 0,
'attribute' => 'name', // foreign key attribute that is shown to user
'inline_create' => [ // specify the entity in singular
'entity' => 'tag', // the entity in singular
'force_select' => true, // should the inline-created entry be immediately selected?
'modal_class' => 'modal-dialog modal-md', // use modal-sm, modal-lg to change width
'modal_route' => route('tag-inline-create'), // InlineCreate::getInlineCreateModal()
'create_route' => route('tag-inline-create-save'), // InlineCreate::storeInlineCreate()
]
]
);
Question modal
// tags
public function tags()
{
return $this->belongsToMany(Tag::class, 'question_tags', 'question_id', 'tag_id');
}

I finally found the problem.
I needed to define the ajax route to work with the field, either creating my own endpoin, or using FetchOperation https://backpackforlaravel.com/docs/5.x/crud-operation-fetch#about-1.
In QuestionCrudController:
use \Backpack\CRUD\app\Http\Controllers\Operations\FetchOperation;
...
public function fetchTags()
{
return $this->fetch(Tag::class);
}

Related

Laravel Backpack attribute accessor causing bug on update command

I am working on Laravel Backpack. I have two fields like this:
$this->crud->addField([ // SELECT2
'label' => 'Type',
'type' => 'select_from_array',
'name' => 'type',
'options' => [
'' => 'select type',
'Movie' => 'Movies',
'Series' => 'Series'
],
]);
$this->crud->addField([ // select2_from_ajax: 1-n relationship
'label' => "Entity", // Table column heading
'type' => 'select2_from_ajax',
'name' => 'entity_id', // the column that contains the ID of that connected entity;
'entity' => 'entity', // the method that defines the relationship in your Model
'attribute' => 'name', // foreign key attribute that is shown to user
'data_source' => url('api/entity'), // url to controller search function (with /{id} should return model)
'placeholder' => 'Select', // placeholder for the select
'include_all_form_fields' => true, //sends the other form fields along with the request so it can be filtered.
'minimum_input_length' => 0, // minimum characters to type before querying results
'dependencies' => ['type'], // when a dependency changes, this select2 is reset to null
// 'method' => 'GET', // optional - HTTP method to use for the AJAX call (GET, POST)
]);
The second field options are dependent on the first one.
In my model, I have:
public function getEntityIdAttribute()
{
$id = $this->attributes['entity_id'];
$type = $this->attributes['type'];
if ($type == "Movie") {
$attribute = Movie::find($id);
} else {
$attribute = Series::find($id);
}
return $attribute->name;
}
Create and List operations work perfectly. But on update, it throws this error:
Undefined array key "entity_id"
Why is this accessor not working on the update? or can we somehow skip the accessor on the update command?

How to sort by related table field when sending Yii2 REST GET request

I want to expand this question.
Basically I have users endpoint. But I am also returning data from the related profiles table. I am not expanding with profiles, I always want to return it. So I have fields method like this:
public function fields()
{
$fields = parent::fields();
$fields[] = 'profile';
return $fields;
}
When I do GET request and demand sorting by profile.created_at field and user.status, it does not sort by profile.created_at.
GET v1/users?sort=-profile.created_at,status
Can this be achieved somehow ?
This is my current code:
/** #var $query ActiveQuery */
$query = User::find();
// get data from profile table
$query->innerJoinWith('profile');
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => ['defaultOrder' => ['id' => SORT_DESC]],
'pagination' => [
'pageSize' => 10,
],
]);
return $dataProvider;
You have overridden 'sort' parameter of ActiveDataProvider. To keep default behaviour of Sort object and change defaultOrder property, create an instance, such as:
$sort = new \yii\data\Sort([
'attributes' => [
'profile.created_at',
],
'defaultOrder' => ['id' => SORT_DESC],
]);
// add conditions that should always apply here
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort' => $sort,
'pagination' => [
'pageSize' => 10,
],
]);

Prestashop helper form 'file' type

I m working on prestasshop and I created a helper form inside a controller (for back office). My question is how to upload a document by using the type:'file' from the helper form. Here is the code:
public function __construct()
{
$this->context = Context::getContext();
$this->table = 'games';
$this->className = 'Games';
$this->lang = true;
$this->addRowAction('edit');
$this->addRowAction('delete');
$this->bulk_actions = array('delete' => array('text' => $this->l('Delete selected'),
'confirm' => $this->l('Delete selected items?')));
$this->multishop_context = Shop::CONTEXT_ALL;
$this->fieldImageSettings = array(
'name' => 'image',
'dir' => 'games'
);
$this->fields_list = array(
'id_game' => array(
'title' => $this->l('ID'),
'width' => 25
)
);
$this->identifier = 'id_game';
parent::__construct();
}
public function renderForm()
{
if (!($obj = $this->loadObject(true)))
return;
$games_list = Activity::getGamesList();
$this->fields_form = array(
'tinymce' => true,
'legend' => array(
'title' => $this->l('Game'),
'image' => '../img/admin/tab-payment.gif'
),
'input' => array(
array(
'type' => 'select',
'label' => $this->l('Game:'),
'desc' => $this->l('Choose a Game'),
'name' => 'id_games',
'required' => true,
'options' => array(
'query' => $games_list,
'id' => 'id_game',
'name' => 'name'
)
),
array(
'type' => 'text',
'label' => $this->l('Game Title:'),
'name' => 'name',
'size' => 64,
'required' => true,
'lang' => true,
'hint' => $this->l('Invalid characters:').' <>;=#{}'
),
array(
'type' => 'file',
'label' => $this->l('Photo:'),
'name' => 'uploadedfile',
'id' => 'uploadedfile',
'display_image' => false,
'required' => false,
'desc' => $this->l('Upload your document')
)
)
);
$this->fields_form['submit'] = array(
'title' => $this->l(' Save '),
'class' => 'button'
);
return AdminController::renderForm();
}
Now how can I upload the document?
Do I have to create a column in the table of the db (games table) for storing the file or something related?
Thanks in advance
I assume this AdminController for your model. Now a model obviously can't hold a file in table column. What you can do is hold path to the uploaded file. That's what you can save.
You should look in AdminController class (which you extended). When you submit a form, one of two method are executed:
processAdd()
processUpdate()
Now investigate the flow logic in these methods. Other methods are called from within this methods, such as:
$this->beforeAdd($this->object); -> calls $this->_childValidation();
$this->validateRules();
$this->afterUpdate($object);
As you can see, there these are the methods where you can do you custom stuff. If you look up these functions in AdminController class, the're empty. They are purposely added so people can override them and put their custom logic there.
So, using these functions, you can validate your uploaded file fields (even though it isnt in the model itself), if it validates you can then assign path to the object; and then in beforeAdd method you can actually move the uploaded file to the desired location (because both child validation and default validation has passed).
The way I've done it:
protected function _childValidation()
{
// Check upload errors, file type, writing permissions
// Use $this->errors['file'] if there is an error;
protected function beforeAdd($object)
{
// create filename and filepath
// assign these fields to object;
protected function afterAdd($object)
{
// move the file
If you allow the file field to be updated, you'll need to to these steps for Update methods as well.
you can get uploaded file using $_FILES['uploadedfile'] in both the functions processAdd() and processUpdate(), you can check all the conditions there and before calling $this->object->save(); to save the form data you can write the code to upload the file in the desired location like
move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)
since you can't save the file in database you need to save only the name of the file or location on the database
Hope that helps

Module Forms - Store Value of addField to a Variable

I have something like in my custom module:
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $order_id)),
'value' => 'Magento Blog',
'after_element_html' => '',
));
And as you can see from the code, I am trying to link that field to the Order Tab in the back-end. I'm having trouble getting the ID though. I'm planning to just save the Order ID in the database, and then using the addField I could have the correct url.
But how can I save an addField value to a variable?
I want to store the value in "$order_id".
Is it possible?
I am not sure in which context you are using this fieldset but if it is used for example for creating or editing object you can try something like that:
In controller:
public function editAction()
{
$id = $this->getRequest()->getParam('id');
$model = Mage::getModel('module/model')->load($id);
Mage::register('model_name', $model);
}
and then in the block:
protected function _prepareForm()
{
$model = Mage::registry('model_name');
// add fieldset to form
$fieldset->addField('orderinfo', 'link', array(
'label' => Mage::helper('web')->__('Order Info'),
'style' => "",
'href' => Mage::helper('adminhtml')->getUrl('adminhtml/sales_order/view', array('order_id' => $model->getOrderId())),
'value' => 'Magento Blog',
'after_element_html' => '',
));
//rest of the elements
}
Answering my own post again. (src: https://magento.stackexchange.com/questions/682/module-forms-store-value-of-addfield-to-a-variable)

How to edit cell Zfdatagrid

how I can make editing row using ajax with zfdatagrid, thanks
ZF 1.11 -
My Bootstrap
protected function _initZfdatagrid()
{
$this->_config = new Zend_Config_Ini(APPLICATION_PATH .'/configs/grid.ini', 'production');
Zend_Registry::set('config', $this->_config);
if ( #isset(Zend_Registry::get('config')->site->jqGridUrl) ) {
Bvb_Grid_Deploy_JqGrid::$defaultJqGridLibPath = Zend_Registry::get('config')->site->jqGridUrl;
}
}
My Controller
public function indexAction()
{
$grid1 = new Bvb_Grid_Deploy_JqGrid(Zend_Registry::get('config'));
$this->configG1($grid1);
$grid1->setDeployOptions(array
('title'=>'Grado 10A',
'subtitle'=>'School2.0 : Matematicas:'.date('Y-m-d'),
'logo'=>$this->view->baseUrl.'/zfdatagrid/public/images/logotipo.jpg',
));
$this->view->grid = $grid1->deploy();
$this->render('index');
}
public function configG1 ($grid)
{
$select = $this->_db->select()->from('Articulos', array('id', 'titulo', 'fecha','nota', 'publicar', 'dependencia'));
$grid->setSource(new Bvb_Grid_Source_Zend_Select($select));
$grid->updateColumn('id',
array('title' => '#ID', 'hide' => true));
$grid->updateColumn('_action',
array('search' => false, // this will disable search on this field
'order' => 1, 'title' => 'Action', 'width' => 100, 'class' => 'bvb_action bvb_first', 'callback' =>
array('function' => array($this, 'g1ActionBar'), 'params' =>
array('{{ID}}')), 'jqg' =>
array('fixed' => true, 'search' => false)));
$grid->updateColumn('titulo', array('title' => 'Titulo Articulo', 'width' => 260));
$grid->updateColumn('fecha', array('title' => 'Fecha', 'searchType' => "="));
$grid->updateColumn('Nota', array('title' => 'Calificacion (ucase)', 'callback' => array('function' => create_function('$text', 'return strtoupper($text);'), 'params' => array('{{District}}'))));
$grid->setDefaultFilters(array('titulo' => '1'));
$grid->setExport(array(// define parameters for csv export, see Bvb_Grid::getExports
'csv' => array('caption' => 'Csv'),
'pdf' => array('caption' => 'Pdf')));
$grid->setJqgParams(array('caption' => 'jqGrid Example', 'forceFit' => true, 'viewrecords' => false, // show/hide record count right bottom in navigation bar
'rowList' => array(10, 20, 30, 40, 50), // show row number per page control in navigation bar
'altRows' => true)// rows will alternate color
);
$grid->setJqgParam('viewrecords', true);
$grid->jqgViewrecords = true;
$grid->setBvbParams(array('id' => 'ID'));
$grid->setBvbParam('id', 'ID');
$grid->bvbId = 'ID';
$grid->bvbOnInit = 'console.log("this message will not be logged because of call to bvbClearOnInit().");';
$grid->bvbClearOnInit();
$grid->bvbSetOnInit('console.log("jqGrid initiated ! If data are remote they are not loaded at this point.");');
$grid->setAjax(get_class($grid));
}
If you haven't gotten anywhere on this, you might want to look at the jqgrid wiki. They provide information on adding inline cell editing:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:cell_editing
as well as popup form editing:
http://www.trirand.com/jqgridwiki/doku.php?id=wiki:form_editing
According to the inline cell editing page, adding the cellEdit parameter should enable cell editing. You can provide the url the data is submit to with the cellurl parameter.