Getting Matrix field ID and Block ID for my Custom Field
The BaseFieldType class (which all FieldTypes extend) has a contentPostLocation property, which will give you the "path" to the field inside the entry model. The value is returned as a string, e.g. fields.myCustomFieldTypeHandle.

If your field is inside a Matrix block, the contentPostLocation path will include the Matrix field's handle – as well as the block ID – e.g. 

fields.matrixFieldHandle.12.fields.myCustomFieldTypeHandle

Based on this, by exploding the contentPostLocation string and testing its length, you can figure out if the field is "standalone" or embedded in a Matrix block:

$contentPath = explode('.', $this-&gt;contentPostLocation);
if (count($contentPath) &gt; 2) {
    // Not standalone (i.e. probably inside a Matrix block)
}


The Matrix' field's handle will be the second segment in the path. You can use the FieldsService to pull the actual field, in order to get its ID. It's probably also a good idea to confirm that it is indeed a Matrix field, which is easily done by checking its fieldtype's classHandle property:

$matrixFieldHandle = $path[1];
$matrixField = craft()-&gt;fields-&gt;getFieldByHandle($matrixFieldHandle);
if ($matrixField &amp;&amp; $matrixField-&gt;fieldType-&gt;classHandle === 'Matrix')
{
    // Yup, it's a Matrix field!
    $matrixFieldId = $matrixField-&gt;id;
}


Finally, the block ID would be the next segment in the contentPostLocation path, i.e. $matrixBlockId = (int) $contentPath[2];

Putting it all together, something like this should do the trick:

public function onAfterElementSave()
{
    $contentPath = explode('.', $this-&gt;contentPostLocation);
    if (count($contentPath) &gt; 2)
    {
        $matrixFieldHandle = $contentPath[1];
        $matrixField = craft()-&gt;fields-&gt;getFieldByHandle($matrixFieldHandle);
        if ($matrixField &amp;&amp; $matrixField-&gt;fieldType-&gt;classHandle === 'Matrix')
        {
            $matrixFieldId = $matrixField-&gt;id;
            $matrixBlockId = (int) $contentPath[2];
        }
    }
}