Even if I don't see the point (but maybe I'm not that artistic) this can be done easily.
First you need to remove the add button from the grid container block. This should be the block: {Namespace}/{Module}/Block/Adminhtml/{Entity}.php
. At the end of the __construct
method add this line:
$this->removeButton('add');
Now you need to add a button near the search button. For this you should add a method called getMainButtonsHtml
in your grid block. This is {Namespace}/{Module}/Block/Adminhtml/{Entity}/Grid.php
public function getMainButtonsHtml()
{
$html = parent::getMainButtonsHtml();//get the parent class buttons
$addButton = $this->getLayout()->createBlock('adminhtml/widget_button') //create the add button
->setData(array(
'label' => Mage::helper('adminhtml')->__('Add'),
'onclick' => "setLocation('".$this->getUrl('*/*/new')."')",
'class' => 'task'
))->toHtml();
return $addButton.$html;
}
That's it. Happy button aligning.
If you define grid collection thought layout than you can use updater to add default filter.
<argument name="dataSource" xsi:type="object">
Tutorial\SimpleNews\Model\Resource\News\Collection
<updater>Tutorial\SimpleNews\Model\Resource\News\Collection\Updater</updater>
</argument>
and
<?php
namespace Tutorial\SimpleNews\Model\Resource\News\Collection;
class CollectionUpdater implements \Magento\Framework\View\Layout\Argument\UpdaterInterface
{
/**
* Update grid collection according to chosen order
*
* @param \Tutorial\SimpleNews\Model\Resource\News\Collection $argument
* @return \Tutorial\SimpleNews\Model\Resource\News\Collection
*/
public function update($argument)
{
$argument->addFieldToFilter('you_field', 'value');
return $argument;
}
}
or Extend Grid block
class Grid extends \Magento\Backend\Block\Widget\Grid
{
protected function _prepareCollection()
{
if ($this->getCollection()) {
foreach ($this->getDefaultFilter() as $field => $value) {
$this->getCollection()->addFieldToFilter($field, $value);
}
}
return parent::_prepareCollection();
}
}
Best Answer